package com.guoqi.keepsign.album

import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Environment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.donkor.deepnight.utils.ImageLoadUtils
import com.donkor.deepnight.utils.showToast
import com.guoqi.keepsign.base.ImageInfo
import com.guoqi.keepsign.previewlibrary.GPreviewBuilder
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Response
import java.io.File


class AlbumAdapter(context: Activity?, list: ArrayList<ImageInfo>, layoutManager: GridLayoutManager) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val TAG = "AlbumAdapter"

    var mContext: Activity? = null
    private var mInflater: LayoutInflater? = null
    var imageList: ArrayList<ImageInfo>? = null
    var gm: GridLayoutManager? = null

    init {
        mContext = context
        imageList = list
        mInflater = LayoutInflater.from(context)
        gm = layoutManager
    }


    override fun getItemCount(): Int {
        return imageList?.size ?: 0
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return CommonHolder(mInflater?.inflate(com.guoqi.keepsign.R.layout.item_common, parent, false)!!)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is CommonHolder) {
            holder.tvTitle.setBackgroundColor(0)
            ImageLoadUtils.display(mContext, holder.ivPic, imageList?.get(position)?.url)
            holder.ivPic.setOnClickListener {
                if (imageList?.get(position)?.url.isNullOrEmpty()) {
                    mContext?.showToast("链接失效")
                } else {
                    computeBoundsBackward(position)
                    GPreviewBuilder.from(mContext!!)
                            .setOnDownImageListener { url, v ->
                                downloadImage(url, v)
                            }
                            .setData(imageList!!)
                            .setCurrentIndex(position)
                            .setType(GPreviewBuilder.IndicatorType.Number)
                            .start()
                }
            }
        }
    }

    private fun downloadImage(url: String, v: View) {
        mContext?.showToast("开始下载")
        v.visibility = View.GONE
        val myFileCallback: FileCallback = object : FileCallback(getPath(), "") {
            override fun onSuccess(response: Response<File>?) {
                val file = response?.body() as File
                mContext?.showToast("已保存到 /GrassPic/ 下")
                val uri = Uri.fromFile(file)
                mContext?.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            }

            override fun onError(response: Response<File>?) {
                Log.e(TAG, response?.exception?.message)
                mContext?.showToast("下载出错")
                v.visibility = View.VISIBLE
            }
        }
        OkGo.get<File>(url)
                .headers("cookie", "Hm_lvt_dbc355aef238b6c32b43eacbbf161c3c=1536981553; Hm_lpvt_dbc355aef238b6c32b43eacbbf161c3c=1536986863")
                .headers("Referer", url)
                .execute(myFileCallback)
    }

    class CommonHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var ivPic: ImageView = itemView?.findViewById<ImageView>(com.guoqi.keepsign.R.id.iv_pic) as ImageView
        var tvTitle: TextView = itemView?.findViewById<TextView>(com.guoqi.keepsign.R.id.tv_title) as TextView
    }


    /**
     * 计算返回的图片边框
     */
    private fun computeBoundsBackward(firstCompletelyVisiblePos: Int) {
        for (i in firstCompletelyVisiblePos until imageList!!.size) {
            val itemView = gm!!.findViewByPosition(i)
            val bounds = Rect()
            if (itemView != null) {
                val thumbView = itemView!!.findViewById(com.guoqi.keepsign.R.id.iv_pic) as ImageView
                thumbView.getGlobalVisibleRect(bounds)
            }
            (imageList as ArrayList<ImageInfo>)[i].setBounds(bounds)
        }
    }

    /**
     * 文件下载路径
     */
    fun getPath(): String {
        var imagePath = Environment.getExternalStorageDirectory().absolutePath + File.separator + "GrassPic"
        val file = File(imagePath)
        return if (file.mkdirs()) {
            imagePath
        } else imagePath
    }
}